import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from "@nestjs/websockets";
import { Server, WebSocket } from "ws";
import {EventEmitter2, EventEmitterModule} from '@nestjs/event-emitter';
import {EnumEvents} from "../../../../types/constants";


@WebSocketGateway(9093)
export class WsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  private client: WebSocket;
  constructor(private eventEmitter: EventEmitter2 ) {
  }
  @WebSocketServer()
  server: Server;

  @SubscribeMessage("message")
  handleMessage(client: WebSocket, payload: any): string {
    console.log("Message received:", payload);
    return "Hello world!";
  }

  handleConnection(client: WebSocket) {
    this.client = client;
    console.log("Client connected:");
  }

  handleDisconnect(client: WebSocket) {
    if (this.client === client) {
      this.client = null;
    }
    console.log("Client disconnected:");
    this.eventEmitter.emit(EnumEvents.breathClientDisconnect);
  }

  sendMsg(msg: any) {
    if (this.client && this.client.readyState === WebSocket.OPEN) {
      this.client.send(JSON.stringify(msg));
    }
  }
}
